package han.yang.service.friendship.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import han.yang.common.ResponseVO;
import han.yang.common.enums.ApproveFriendRequestStatusEnum;
import han.yang.common.enums.FriendShipErrorCode;
import han.yang.common.exception.ApplicationException;
import han.yang.service.friendship.dao.ImFriendShipRequestEntity;
import han.yang.service.friendship.dao.mapper.ImFriendShipRequestMapper;
import han.yang.service.friendship.model.dto.FriendDto;
import han.yang.service.friendship.model.req.ApproverFriendRequestReq;
import han.yang.service.friendship.model.req.ReadFriendShipRequestReq;
import han.yang.service.friendship.service.ImFriendService;
import han.yang.service.friendship.service.ImFriendShipRequestService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 好友申请相关逻辑
 * @author yanghan
 * @date 2023/3/13
 */
@Service
public class ImFriendShipRequestServiceImpl implements ImFriendShipRequestService {

    @Resource
    ImFriendShipRequestMapper imFriendShipRequestMapper;

    @Resource
    ImFriendService imFriendService;

    @Override
    public ResponseVO<?> addFriendShipRequest(String fromId, FriendDto dto, Integer appId) {
        // 首先查询申请记录是否存在，如果存在则修改申请时间与申请备注即可
        QueryWrapper<ImFriendShipRequestEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("from_id",fromId)
                .eq("to_id",dto.getToId())
                .eq("app_id",appId)
                .eq("approve_status",0);
        ImFriendShipRequestEntity entity = imFriendShipRequestMapper.selectOne(queryWrapper);
        if (entity != null){
            entity.setCreateTime(System.currentTimeMillis());
            entity.setRemark(dto.getRemark());
            entity.setAddSource(dto.getAddSource());
            entity.setAddWording(dto.getAddWording());
            imFriendShipRequestMapper.update(entity, queryWrapper);
        }else {
            entity = new ImFriendShipRequestEntity();
            entity.setFromId(fromId);
            entity.setToId(dto.getToId());
            entity.setAppId(appId);
            entity.setRemark(dto.getRemark());
            entity.setAddWording(dto.getAddWording());
            entity.setCreateTime(System.currentTimeMillis());
            imFriendShipRequestMapper.insert(entity);
        }
        return ResponseVO.successResponse();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseVO<?> approverFriendRequest(ApproverFriendRequestReq req) {
        // 获取好友申请记录的实体
        ImFriendShipRequestEntity imFriendShipRequestEntity = imFriendShipRequestMapper.selectById(req.getId());
        if (imFriendShipRequestEntity == null){
            throw new ApplicationException(FriendShipErrorCode.FRIEND_REQUEST_IS_NOT_EXIST);
        }
        // 判断操作人,只能审批自己的好友请求
        if (!req.getOperater().equals(imFriendShipRequestEntity.getToId())){
            throw new ApplicationException(FriendShipErrorCode.NOT_APPROVER_OTHER_MAN_REQUEST);
        }
        // 修改状态
        imFriendShipRequestEntity.setApproveStatus(req.getStatus());
        imFriendShipRequestEntity.setUpdateTime(System.currentTimeMillis());
        imFriendShipRequestMapper.updateById(imFriendShipRequestEntity);
        if (ApproveFriendRequestStatusEnum.AGREE.getStatus().equals(req.getStatus())){
            // 同意好友添加，在好友表插入数据
            // 如果是拒绝，则不需要进行下一步操作，只修改申请表的状态
            FriendDto dto = new FriendDto();
            dto.setAddSource(imFriendShipRequestEntity.getAddSource());
            dto.setAddWording(imFriendShipRequestEntity.getAddWording());
            dto.setRemark(imFriendShipRequestEntity.getRemark());
            dto.setToId(imFriendShipRequestEntity.getToId());
            // 执行ImFriendShip中的双向添加逻辑
            ResponseVO<?> responseVO = imFriendService.doAddFriend(req,imFriendShipRequestEntity.getFromId(),req.getAppId(),dto);
            if (!responseVO.isOk() && responseVO.getCode() != FriendShipErrorCode.TO_IS_YOUR_FRIEND.getCode()){
                return responseVO;
            }
        }
        return ResponseVO.successResponse();
    }

    @Override
    public ResponseVO<?> readFriendShipRequestReq(ReadFriendShipRequestReq req) {
        QueryWrapper<ImFriendShipRequestEntity> query = new QueryWrapper<>();
        query.eq("app_id", req.getAppId());
        query.eq("to_id", req.getFromId());
        ImFriendShipRequestEntity update = new ImFriendShipRequestEntity();
        // 设置状态为已读
        update.setReadStatus(1);
        imFriendShipRequestMapper.update(update, query);
        return ResponseVO.successResponse();
    }

    @Override
    public ResponseVO<?> getFriendRequest(String userId, Integer appId) {
        List<ImFriendShipRequestEntity> requestList = imFriendShipRequestMapper.getAllRequest(appId,userId);
        return ResponseVO.successResponse(requestList);
    }

}